import { Body, Controller, Post, UseGuards, Request } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AIService } from './ai.service';
import { GenerateResponseDto, TTSRequestDto, ASRRequestDto } from './dto/ai.dto';

@ApiTags('AI')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('ai')
export class AIController {
  constructor(private readonly aiService: AIService) {}

  // Generate AI response
  @Post('generate')
  @ApiOperation({ summary: 'Generate AI response' })
  @ApiResponse({ status: 200, description: 'Generation successful' })
  @ApiResponse({ status: 400, description: 'Invalid request parameters' })
  async generateResponse(@Body() dto: GenerateResponseDto) {
    return this.aiService.generateResponse(
      dto.messages,
      dto.personaPrompt,
      dto.model
    );
  }

  // Text-to-speech conversion
  @Post('tts')
  @ApiOperation({ summary: 'Text-to-speech conversion' })
  @ApiResponse({ status: 200, description: 'Conversion successful' })
  @ApiResponse({ status: 400, description: 'Invalid request parameters' })
  async textToSpeech(@Body() dto: TTSRequestDto) {
    return this.aiService.textToSpeech(
      dto.text,
      dto.voice,
      dto.format,
      dto.language
    );
  }

  // Speech-to-text conversion
  @Post('asr')
  @ApiOperation({ summary: 'Speech-to-text conversion' })
  @ApiResponse({ status: 200, description: 'Conversion successful' })
  @ApiResponse({ status: 400, description: 'Invalid request parameters' })
  async speechToText(@Body() dto: ASRRequestDto) {
    // Convert base64 to ArrayBuffer
    const rawBase64 = dto.audioData.includes(',')
      ? dto.audioData.split(',').pop() as string
      : dto.audioData;
    const audioBuffer = Buffer.from(rawBase64, 'base64');
    return this.aiService.speechToText(
      audioBuffer.buffer.slice(audioBuffer.byteOffset, audioBuffer.byteOffset + audioBuffer.byteLength),
      dto.language,
      dto.mimeType
    );
  }

  // Check AI service health status
  @Post('health')
  @ApiOperation({ summary: 'Check AI service health status' })
  @ApiResponse({ status: 200, description: 'Health check completed' })
  async checkHealth() {
    return this.aiService.checkServiceHealth();
  }
}
